# from String import String
# from docx import Document
# import win32com.client as wc
# import xlrd
# import openpyxl
# import shutil
# import tempfile
# from zipfile import ZipFile
# from pathlib import Path
# from time import sleep
# from pptx import Presentation
# from PyPDF2 import PdfFileReader
# import pdfplumber
# import xmind

def readDocxFile(path):
    document = Document(path)
    result = ""
    for paragraph in document.paragraphs:
        result += paragraph.text + "\n"
    for tb in document.tables:
        for row in tb.rows:
            for cell in row.cells:
                result += cell.text + "\t"
            result += "\n"
        result += "\n"
    for child in document.element.body.iter():
        if child.tag.endswith('textbox'):
            for c in child.iter():
                c_tag = c.tag
                if c_tag.endswith('main}r'):
                    result += c.text + '\n'
            result += '\n'
    return result

def readDocFile(path):
    word = wc.Dispatch('Word.Application')
    doc = word.Documents.Open(path)
    newPath = path + "x"
    if os.path.exists(newPath):
        newPath= path[:-4] + "_temp" + path[-4:] + "x"
        doc.SaveAs(newPath, 12, False, "", True, "", False, False, False, False)
    else: doc.SaveAs(newPath, 12, False, "", True, "", False, False, False, False)
    doc.Close()
    word.Quit()
    result = readDocxFile(newPath)
    os.remove(newPath)
    return result

def read_xlsx_textbox_text(xlsx_file):
    tempdir = tempfile.gettempdir()
    basename = os.path.basename(xlsx_file)
    xml_names = []
    with ZipFile(xlsx_file) as zip_file:
        for name in zip_file.namelist():
            if name.startswith("xl/drawings/drawing"):
                zip_file.extract(name, tempdir)
                destname = f"{tempdir}/{name}"
                xml_names.append(destname)
    result = []
    for xml_name in xml_names:
        with open(xml_name, encoding="utf-8") as f:
            text = f.read()
        lines = re.findall("<a:p>(.*?)</a:p>", text)
        for line in lines:
            runs = re.findall("<a:t>(.*?)</a:t>", line)
            result.append("".join(runs).replace('&lt;', '<').replace(
                '&gt;', '>').replace('&amp;', '&'))
    return "\n".join(result)

def read_xls_textbox_text(xls_file):
    excel_app = wc.gencache.EnsureDispatch('Excel.Application')
    # excel_app.DisplayAlerts = False
    try:
        wb = excel_app.Workbooks.Open(xls_file)
        xlsx_file = xls_file + "x"
        if os.path.exists(xlsx_file):
            xlsx_file = xls_file[:-4] + "_temp" + xls_file[-4:] + "x"
            wb.SaveAs(xlsx_file, FileFormat=51)
        else: wb.SaveAs(xlsx_file, FileFormat=51)
    finally:
        excel_app.Quit()
    result = read_xlsx_textbox_text(xlsx_file)
    sleep(0.1)
    os.remove(xlsx_file)
    return result

def readXlsFile(path):
    workbook = xlrd.open_workbook(path)
    sheet_names = workbook.sheet_names()
    result = ""
    for sheet_name in sheet_names:
        sheet = workbook.sheet_by_name(sheet_name)
        for row in range(sheet.nrows):
            for col in range(sheet.ncols):
                result += sheet.cell_value(row, col) + "\t"
            result += "\n"
    result += read_xls_textbox_text(path) + "\n"
    return result

def readXlsxFile(path):
    book = openpyxl.load_workbook(path)
    result = ""
    for sheet in book.worksheets:
        for row in range(1, sheet.max_row + 1):
            for col in range(1, sheet.max_column + 1):
                result += str(sheet.cell(row, col).value) + "\t"
            result += "\n"
    result += read_xlsx_textbox_text(path) + "\n"
    return result

def readPptFile(path):
    pnt = wc.Dispatch('PowerPoint.Application')
    wc.gencache.EnsureDispatch('PowerPoint.Application')
    pnt.Visible = 1
    ppt = pnt.Presentations.Open(path)
    newPath = path + "x"
    if os.path.exists(newPath):
        newPath= path[:-4] + "_temp" + path[-4:] + "x"
        ppt.SaveAs(newPath)
    else: ppt.SaveAs(newPath)
    ppt.Close()
    pnt.Quit()
    result = readPptxFile(newPath)
    os.remove(newPath)
    return result

def readPptxFile(path):
    prs = Presentation(path)
    result = ""
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                text_frame = shape.text_frame
                result += text_frame.text + "\n"
            if shape.has_table:
                t = shape.table
                for row in t.rows:
                    for cell in row.cells:
                        result += cell.text + "\t"
                    result += "\n"
            #if shape.has_chart:
                #t = shape.chart
                #print(dir(t))
    return result

def readPdfFile1(path):
    pdf = PdfFileReader(open(path, "rb"))
    result = ""
    count = 0
    for i in range(0, pdf.getNumPages()):
        pageObj = pdf.getPage(i)
        extractedText = pageObj.extractText()
        print(type(extractedText))
        #result += str(extractedText, encoding = "utf-8") + "\n"
        #extractedText = extractedText.encode('latin-1')
        #extractedText = extractedText.decode('gbk')
        result += extractedText + "\n"
        count += 1
        if 1 == count: break
    return result

def readPdfFile2(path):
    with open(path,'rb') as pdf_html:
        parser = PDFParser(pdf_html)
    doc = PDFDocument()
    parser.set_document(doc)
    doc.set_parser(parser)
    rsrcmagr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmagr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmagr, device)
    result = ""
    for page in doc.get_pages():
        interpreter.process_page(page)
        layout = device.get_result()
        for x in layout:
            if(isinstance(x, LTTextBoxHorizontal)):
                result += x.get_text() + "\n"
    return result

def readPdfFile(path):
    result = ""
    with pdfplumber.open(path) as pdf:
        for page in pdf.pages:
            result += page.extract_text() + "\n"
    return result

def readXmindFile(path):
    workbook = xmind.load(path)
    result = ""
    for sheet in workbook.getSheets():
        data = sheet.getData()
        result += str(data) + "\n"
        #result += json.dumps(data, indent=4, separators=(',', ': ')) + "\n"
    return result

